// 永劫无间 首图 详情图 生成
import { getURLBase64Image, loadImages, drawImagesAreaBg,drawBgBorder } from "./getUrlImg";

// 生成永劫无间首图
export async function makeTitleImgYjwj(data, list, attrs) {
  return new Promise(async (resolve, reject) => {
    // 取出已选择项
    let arr = [];
    let sm = "";
    let gzdj = "";
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }
    if (list && list.length) {
      attrs.forEach(async (item1) => {
        if (item1.aavName == "f16") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f16) {
              sm = item2.fieldName;
            }
          });
        }
        if (item1.aavName == "f2") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f2) {
              gzdj = item2.fieldName;
            }
          });
        }
        if (item1.fieldType == "checkbox" && item1.isEnable === "0") {
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1 && item2.imgUrl) {
              const nameArr = arr.map(a=>a.fieldName)
              if(!nameArr.includes(item2.fieldName)){
                arr.push(item2);
              } 
            }
          });
        }
      });
    }

    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/yjwj/titleImgBg.png"
      );
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#ffffff";
      // // 头部标题 店铺名
      // context.font = "bold 50px Adobe Ming Std";
      // // 头部标题 店铺名
      // context.fillText(
      //   `${data.gameName || "--"}`,
      //   2560 / 2 - (data.gameName.length * 48) / 2,
      //   70
      // );
      // 左侧展示
      context.font = "bold 45px Adobe Ming Std";
      // 1、编号  2、区服 3、使命 4、贵族 5、皮肤数量 6、英雄数量  7、典藏数量
      context.fillText(`${data.thirdId || "--"}`, 240, 393); //编号
      context.fillText(`${data.f47 || "--"}`, 384, 525);//通行证等级
      context.fillText(`${data.f48 || "--"}`, 240, 655);//段位
      context.fillText(`${data.f49 || "--"}`, 240, 783);//等级
      context.fillText(`${data.f41 || "--"}`, 288, 910);//红品数
      context.fillText(`${data.f50 || "--"}`, 288, 1040);//金品数
      context.fillText(`${data.f51 || "--"}`, 288, 1167);//幻丝数
      //  加载皮肤图片
      context.font = "28px Adobe Ming Std";
      let skinImgs = [];
      if (arr && arr.length) {
        arr.sort((a, b) => b.sort - a.sort);
        skinImgs = await loadImages(arr, 21);
      } else {
        // 没有Sren
      }
      // .sort(sortBy("sort"))
      // let instances = skinImgs.length ? skinImgs : [];
      if (skinImgs && skinImgs.length) {
        // 开始绘制
        const bg1 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/yjwj/skinjinse.png"
        );
        const bg2 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/yjwj/skinBg.png"
        );
        let opts = {
          startX: 790,
          startY: 256,
          rowNum:7,
          stepY: 32,
          stepX: 24,
          txtLineHeight: 60,
          imgWidth1: 216,
          imgHeight: 336,
          skinImgWidth:174,
          skinImgHeight:232,
          txtInside:true,
          defaultSkinbg:bg1,
          bgImgs: [bg1, bg2],
          textColor:'#fff',
          textWrap:true,
          textRowNum:7
        };
        
        drawImagesAreaBg(context, skinImgs, opts);
        // 绘制结束
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      } else {
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      }
    } catch (error) {
      reject(error);
    }
  });
}


// // 生成详情图-永劫无间 多图
export async function makeDetailImgYJWJ(data, skins, attrs) {
  // console.log("%c Line:147 🍯 attrs", "color:#3f7cff", attrs);
  // console.log("%c Line:147 🍢 skins", "color:#2eafb0", skins);
  // console.log("%c Line:147 🥪 data", "color:#2eafb0", data);
  // data = smock.xqData
  // skins = smock.skins
  // attrs = smock.xqAttrs
  return new Promise(async (resolve, reject) => {
    // 处理实名
    let shimingList = attrs.filter((i) => {
      return i.aavName == "f1";
    });
    let sm = "";
    if (shimingList.length && data.f1) {
      sm = shimingList[0].childAttributes.filter((i) => {
        return i.id == data.f1;
      });
    }

    data.sm = sm && sm.length ? sm[0].fieldName : "--";

    // 分页数据
    let {opts,imgPageArr} = await setPageImgArr(skins)
    // 下载背景图
    let defaultSkinbg = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/defaultSkinbg.png"
    );
    let bg1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/heping/heping-lan.png"
    );
    let bg2 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/heping/heping-fen.png"
    );
    let bg3 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/heping/heping-cheng.png"
    );
    // let bg4 = await getURLBase64Image(
    //   "https://imgage.maimaihao.com/makeImg/wuWeiQiYue/skinbg4.png"
    // );
    // let bg5 = await getURLBase64Image(
    //   "https://imgage.maimaihao.com/makeImg/wuWeiQiYue/skinbg5.png"
    // );

    // 绘制图片
    let imgsArr = [];
    if (imgPageArr && imgPageArr.length) {
      // console.log("%c Line:184 🥪 imgPageArr", "color:#465975", imgPageArr);
      for (let k = 0; k < imgPageArr.length; k++) {
        let base64Img = await makeDetailImgWwqyOne(
          imgPageArr[k],
          data,
          [bg1, bg1, bg1, bg1, bg1, bg1, bg2, bg3],
          defaultSkinbg,
          opts
        );
        imgsArr.push(JSON.stringify(base64Img));
        if (k == imgPageArr.length - 1) {
          resolve(imgsArr);
        }
      }
    }
  });
}
// 绘制一个 永劫无间 详情图
async function makeDetailImgWwqyOne(typeArr, data, bgImgs, defaultSkinbg,opts) {
  ////console.log("%c Line:203 🍌 typeArr", "color:#93c0a4", typeArr);
  // 先计算当前页图片的高度
  let lineHeight = opts.skinHeight||170;
  let skinHeight = 0;
  let lineNum = 0;
  let skinNum = 0;
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      lineNum = lineNum + Math.ceil(typeMap.skins.length / 7);
      for (let j = 0; j < typeArr[i].skins.length; j++) {
        let url = typeArr[i].skins[j].imgUrl;
        if (url) {
          try {
            skinNum++;
            const temp = await getURLBase64Image(url);
            typeArr[i].skins[j].image = temp;
          } catch (error) {}
        } else {
          typeArr[i].skins.splice(j, 1);
          j--;
        }
      }
    }
  }
  skinHeight = Math.ceil(lineNum * lineHeight) + typeArr.length * opts.typeNameHwight + opts.headHeight; //所有皮肤 包括分类标题的高度  页尾距离
  // 开始创建画布
  let y = 140; //图的绘制时距离上端的距离
  let x = 47; //绘制皮肤时的x距离
  // 创建canvas实例
  const canvas = document.createElement("canvas");
  canvas.style.background = "#ffffff";
  const context = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = Math.ceil(skinHeight);
  context.font = "40px Adobe Ming Std";
  // 下载分类名称背景
  let typeNameBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjy-subtitle-bg.png"
  );
  // 下载主背景
  let mainBgImg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjy-bg.png"
  );
  // 下载头部背景
  let titleBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjy-titlebg2.png"
  );
  // 下载右上角装饰
  let hpjyrg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/heping/hpjyrg.png"
  );
  // 开始绘制

  // 绘制背景图
  context.drawImage(mainBgImg, 0, 0, canvas.width, canvas.height);
  // 绘制标题背景
  context.drawImage(titleBg, 0, 0, canvas.width, 100);
  // 填充标题文字
  context.font = "bold 30px Adobe Ming Std";
  context.fillStyle = "#fff"; // 文字填充颜色
  // 头部标题 店铺名
  context.fillText(
    `${data.gameName || "--"}`,
    canvas.width / 2 - (data.gameName.length * 30) / 2,
    50
  );

  // 绘制主要区域的背景
  drawBgBorder(context, 30, 130, canvas.width - 60, skinHeight - 150, {
    radius: 12,
    borderWidth: 2,
    startColor: "rgba(126, 106, 68, 0.6)",
    endColor: "rgba(75, 60, 31, 0.6)",
    borderColor: "#FFF6E9",
  });
  // 绘制右上角装饰 hpjyrg
  context.drawImage(hpjyrg, 1482, 130, 5, 68);

  //
  // 开始绘制皮肤
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      for (let j = 0; j < typeMap.skins.length; j++) {
        let skin = typeMap.skins[j];
        if (j == 0) {
          // 分组开始  先绘制分类标题图片和分类名
          if (i != 0) {
            y += lineHeight;
          }
          context.drawImage(typeNameBg, 0, y - 100, 337, 229);
          context.font = "28px Adobe Ming Std";
          context.fillStyle = "#ffffff"; // 文字填充颜色
          let name = typeMap.typeName || "其他";
          // let txtWidth = name.length * 28;
          context.fillText(` ${name}`, 60, y + 25);
          y += 60;
          x = 47;
        }
        if (j % 7 == 0 && j != 0) {
          x = 47;
          y += lineHeight;
        }
        // 绘制每张图中的皮肤
        if (skin.image) {
          // 绘制背景图
          if (skin.kz1 && bgImgs[skin.kz1]) {
            const bg = bgImgs[skin.kz1];
            // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
            context.drawImage(bg, x, y, 185, 151);
            context.fillStyle = "#fff"; // 文字填充颜色
          } else {
            if (defaultSkinbg) {
              context.drawImage(defaultSkinbg, x, y, 185, 151);
              context.fillStyle = "#333"; // 文字填充颜色
            }
          }
          // 绘制皮肤图片
          context.drawImage(skin.image, x + 40, y + 10, 105, 100);
          // 皮肤名称
          context.font = "20px Adobe Ming Std";
          context.fillText(
            ` ${skin.fieldName ? skin.fieldName : "未知"}`,
            x,
            y + 138
          );

          // 右上角等级
          if (skin.kz2) {
            context.fillStyle = "#333";
            context.fillText(skin.kz2 + "级", x + 185 - 60, y + 20);
          }
          x += 203;
        }
      }
    }
  }
  return canvas.toDataURL("image/jpeg", 0.8);
}
